<template>
  <section style="margin: 0 auto">
    <template>
      <el-form :inline="true" label-width="80px" style="width: 1280px">
        <el-form-item>
          <el-input placeholder="输入角色名称" style="min-width: 240px;" v-model="nickName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="query()">查询</el-button>
        </el-form-item>
        <!--<el-form-item>-->
          <!--<el-button type="primary" @click="">下载PDF</el-button>-->
        <!--</el-form-item>-->
        <p>注意：数据质量：1代表great、2代表good、3代表qualified、4代表bad</p>
      </el-form>
    </template>
    <el-table border :data="users" style="width: 1222px">
      <el-table-column type="selection" width="110">
      </el-table-column>
      <el-table-column prop="fileId" label="数据ID" width="130">
      </el-table-column>
      <el-table-column prop="userId" label="上传用户ID" width="130">
      </el-table-column>
      <el-table-column prop="nickname" label="上传用户名" width="130">
      </el-table-column>
      <el-table-column prop="remark" label="上传地点" width="130">
      </el-table-column>
      <el-table-column prop="id" label="上传时间" width="130">
      </el-table-column>
      <el-table-column prop="gameName" label="所属数据竞赛" width="130">
      </el-table-column>
      <el-table-column prop="filepath" label="数据内容" width="130">
      </el-table-column>
      <el-table-column prop="evaluate" label="数据质量" width="100" :formatter="formState">
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template  slot-scope="scope">
          <el-button type="success" @click='compile(scope.$index,scope.row)' size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog  :visible.sync="editFormVisible" style="margin:0">
      <el-form :model="form"  :rules="rules" label-width="106px" ref="form" >
        <el-form-item label="数据ID" label-width="100px"class="w">
          <span>{{currentItem.fileId}}</span>
        </el-form-item>
        <el-form-item label="上传用户ID" class="w">
          <span>{{currentItem.userId}}</span>
        </el-form-item>
        <el-form-item label="上传时间" class="w">

        </el-form-item>
        <el-form-item label="上传地点">
          <span>{{currentItem.remark}}</span>
        </el-form-item>
        <el-form-item label="所属数据竞赛" class="w">
          <span>{{currentItem.gameName}}</span>
        </el-form-item>
        <el-form-item label="数据内容">
            <img v-if="currentItem.fileType == 'image'" :src="currentItem.filepath" style="width: 250px;">
            <audio v-else-if="currentItem.fileType == 'audio'" controls :src="currentItem.filepath"></audio>
            <div v-else>未知的文件类型</div>
        </el-form-item>
        <el-form-item label="数据质量" prop="evalation">
          <el-radio-group v-model="form.evalation">
            <el-radio label="1">1（great)</el-radio>
            <el-radio label="2">2（good）</el-radio>
            <el-radio label="3">3（qualified）</el-radio>
            <el-radio label="4">4（bad）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自定义标签" prop="tags">
          <el-select
            v-model="form.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择标签">
            <el-option
              v-for="(item, key) in tags"
              :key="key"
              :label="item.tagName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">立即创建</el-button>
          <el-button type="primary" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div class="block">
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="count" >
      </el-pagination>
    </div>
  </section>
</template>
<script>
  import axios from "axios";
  const staticServer = 'http://47.93.241.106'

  export default {
    data() {
      const validator = (rule, tags, cb) => {
        if (tags.length === 0) {
          return cb(new Error('请输入自定义标签'))
        }

        if (tags.some((tag, i) => {
          if (!/^\d+$/.test(tag)) {
            let temp = tags.slice()
            temp.splice(i, 1)
            return temp.findIndex(_ => _ === tag) > -1
          }
          return false
        })) {
          cb(new Error('自定义标签不能重复'))
        }

        return cb()
      }
      return {
        nickName:'',
        count: 0,
        page: 0,
        users: [],
        tags: [],
        currentItem: {},
        editFormVisible: false,
        form: {
          evalation: '',
          tags: []
        },
        rules: {
          evalation: [
            {required: true, message: '请选择质量'}
          ],
          tags: [{validator}]
        }
      }
    },
    watch: {
      editFormVisible (val) {
        if (!val) {
          this.resetForm()
        }
      }
    },
    methods:{
      formState: function(row) {
        return row.evaluate == 1 ? 'great' : row.evaluate == 2? 'good' :row.evaluate==3? 'qualified':row.evaluate==4? 'bad':'暂无';
      },
      query(){
        this.getTabData();
      },
      handleCurrentChange(val) {
        this.page = val;
        this.getTabData(val);
      },
      getTags () {
        axios.get('/api/getTags')
          .then(res => res.data)
          .then(({code, data = []}) => {
            if (code == 200) {
              this.tags = data
            }
          })
      },
      gameType: function(type) {
        switch (type) {
          case 1:
            return '损坏共享单车拍照收集';
          case 2:
            return '方言语音训练数据收集';
          case 3:
            return '推理游戏意见调查';
          case 4:
            return '发票、小票拍照收集';
          case 5:
            return '城市背景声数据收集';
          case 6:
            return '路况情况拍照征集';
          case 7:
            return 'FIFA世界杯竞赛';
          default:
            return '暂无'
        }
      },
      getTabData: function(index) {
      var _this = this;
      axios.get(
        '/api/getFileList', {
          params:{
            page: index,
            nickName : _this.nickName
          }
        })
        .then(res => res.data)
        .then(({code, data = {}}) => {
          if (code == 200) {
            let list = this.transform(data.rows);

            this.users = list;
            this.count = data.count
          }
        })
        .catch(function(error) {
          console.log(error);
        });

    },
      transform (list) {
        return list.map(item => {
          let {filepath = ''} = item;
          let fileType = 'unknown';
          if (/jpe?g|png|gif$/i.test(filepath)) {
            fileType = 'image'
          }
          if (/amr|mp3|wav|acc$/i.test(filepath)) {
            fileType = 'audio'
          }

          return Object.assign(item, {
            fileType,
            filepath: `${staticServer}${filepath}`,
            gameName: this.gameType(item.gameId)
          })
        })
      },
      compile (index, row) {
        this.currentItem = this.transformItem(row);
        if (this.currentItem.evaluate) {
          this.form.evalation = `${this.currentItem.evaluate}`
        } else {
          this.form.evalation = ''
        }
        this.form.tags = [];
        this.editFormVisible = true;
        if (this.currentItem.evaId) {
          axios.get('/api/getEvaTags',{
            params:{
              evaId: this.currentItem.evaId
            }
          })
            .then(res => res.data)
            .then(({code, msg, data = []}) => {
              if (code === 200) {
                this.form.tags = data.map(tag => tag.id)
              }
            })
            .catch(e => {
            });
        }
      },
      transformItem (row) {
        return Object.assign({}, row, {
          gameName: this.gameType(row.gameId)
        })
      },
      submitForm:function(){
        this.$refs.form.validate(valid => {
          if (valid) {
            axios.post('/api/saveEvalation', {
              evaId: this.currentItem.evaId,
              fileId: this.currentItem.fileId,
              evalation: this.form.evalation,
              tags: this.form.tags
            })
            .then(res => res.data)
            .then(({code, msg}) => {
              if (code === 200) {
                this.editFormVisible = false
                alert('提交成功')
              } else {
                alert(msg)
              }
              this.refresh()
            })
            .catch(e => {
            });
          }
        })
      },
      refresh () {
        this.getTabData()
        this.getTags()
      },
      resetForm () {
        this.form.tags = [];
        this.form.evalation = '';
        this.$refs.form.resetFields()
      }
  },
  mounted(){
    this.refresh()
  }
  }
</script>
<style>
  p{
    text-align: left;
  }
  section{
    padding-left:77px;
  }
  .el-form--inline .el-form-item__label{
    margin-top: -16px;
  }
  .w{
    width: 200px;
  }
  .el-form-item__label {
     font-size: 12px;
     line-height: 6;
   }
  .el-form-item {
     margin-bottom:0;
  }
</style>
